<template>
  <GlobalBG title="告警详情" :showBack="true" :showCollege="false">
    <view class="work-order-detail">
      <view class="work-order-detail-contet">
        <!-- 工单基本信息模块，工单 ID 作为 header -->
        <uni-section
          :title="`工单 ID: ${workOrder.id || ''}`"
          class="section-base"
        >
          <view
            class="info-item"
            v-for="(item, key) in alarmBasicData"
            :key="key"
          >
            <text class="label">{{ key + "：" }}</text>
            <text class="value">{{ item || "--" }}</text>
          </view>
          <view class="info-item">
            <text class="label">相关视频/图片</text>
            <text class="value"></text>
          </view>
        </uni-section>
        <!-- 处理信息模块 -->
        <uni-section title="">
          <uni-forms :model="formData" label-width="90">
            <uni-forms-item label="告警处置情况" class="textarea-desc">
              <view class="deal-status">
                <view class="info-item">
                  <text class="label">处理人：{{ tackleUserName }}</text>
                  <view class="value" v-show="dealPersonData.name">
                    {{
                      dealPersonData.name ||
                      "" + "(" + (dealPersonData.other || "") + ")"
                    }}
                  </view>
                </view>
                <button type="primary" size="mini" @click="dealLineHandler">
                  查看处理过程
                </button>
              </view>
              <!-- <textarea
                v-model="formData.handleDesc"
                placeholder="请输入"
                :maxlength="1000"
              ></textarea>
              <text class="count">{{ formData.handleDesc.length }}/1000</text> -->
            </uni-forms-item>
          </uni-forms>
        </uni-section>
      </view>
      <view class="btn-group">
        <!-- <button class="transfer-btn" @click="handleTransfer">提醒处理</button> -->
        <!-- <button class="submit-btn" @click="handleSubmit">分配工单</button> -->
        <!-- <button class="transfer-btn" @click="hlHandler">忽略</button> -->
        <button
          class="submit-btn"
          @click="handleSubmit"
          v-if="workOrder.worksheet_id == ''"
        >
          分配工单
        </button>

        <button
          class="transfer-btn"
          @click="hlHandler"
          v-if="workOrder.is_ignore !== '1'"
        >
          忽略
        </button>
      </view>
    </view>
  </GlobalBG>
  <ToOtherDeal ref="toOtherDealDialog" dialogTitle="分配工单" />
  <DealLine ref="dealLineDialog" />
</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import { ref } from "vue";
import api from "@/api/modules/home";
import ToOtherDeal from "@/components/ToOtherDeal.vue";
import DealLine from "@/components/DealLine.vue";

const receivedId = ref<string>("");

let alarmBasicData = ref<any>({
  告警时间: "",
  所属专业: "",
  设备名称: "",
  设备编号: "",
  告警级别: "",
  安装位置: "",
  处理人: "",
  自动分配工单: "",
  告警描述: "",
});

let dealPersonData = ref({
  name: "",
  other: "",
});

const tackleUserName = ref<string>("");

const workOrder = ref<any>({
  // id: "",
  // tackleUserName: "",
  // createTime: "2024-10-01 10:00:00",
  // dispatchTime: "2024-10-01 10:30:00",
  // assignPerson: "张三",
  // relatedAlarm: "设备高温告警",
  // faultDesc: "设备运行时出现异常噪音，需检查维修。",
});

const measureOptions = ref([
  { value: 1, text: "重启设备" },
  { value: 2, text: "更换线缆" },
  { value: 3, text: "软件升级" },
  { value: 4, text: "远程调试" },
  { value: 5, text: "现场维修" },
  { value: 1, text: "重启设备" },
  { value: 2, text: "更换线缆" },
  { value: 3, text: "软件升级" },
  { value: 4, text: "远程调试" },
  { value: 5, text: "现场维修" },
]);

const formData = ref({
  handleMeasure: "",
  handleDesc: "",
  images: [],
  video: [],
});

const handleMeasurePopup = ref();

const selectFaultType = (item: { value: string; text: string }) => {
  formData.value.handleMeasure = item.value;
};

onLoad((options) => {
  if (options.id) {
    receivedId.value = options.id;
    console.log("接收到的 id:", receivedId.value);
    // 调用获取工单详情的函数，并传入 receivedId.value
    getWorkOrderDetail(receivedId.value);
  }
});

let currRow = ref();
const getWorkOrderDetail = async (id: string) => {
  try {
    const params = { uuid: id };
    console.log("请求参数:", params);
    let res = await api.alarmGetById(params);
    console.log("获取告警详情", res);

    // 检查响应状态码和数据是否存在
    if (res.code === 0 && res.data) {
      const data = res.data;
      (tackleUserName.value = data.tackle_user_name || ""),
        (workOrder.value = {
          id: data.work_order_code || "",
          is_ignore: data.is_ignore || "0",
          worksheet_id: data.worksheet_id || "",
        });
      alarmBasicData.value = {
        告警时间: data.create_time || "",
        所属专业: data.major_name || "",
        设备名称: data.name || "",
        设备编号: data.code || "",
        告警级别: data.level || "",
        安装位置: data.location_name || "",
        处理人: data.pretreated_user_name || "",
        自动分配工单: data.distribution_form === "自动工单" ? "是" : "否",
        告警描述: data.description || "",
      };
    }
  } catch (error) {
    console.error("获取告警详情失败", error);
  }
};

let toOtherDealDialog = ref();
// const handleSubmit = async () => {
//   toOtherDealDialog.value.open(currRow.value);
// };
const handleSubmit = async () => {
  try {
    toOtherDealDialog.value.open({
      uuid: receivedId.value,
    });

    // 假设分配工单成功后需要重新获取数据
    await getWorkOrderDetail(receivedId.value);
  } catch (error) {
    console.error("分配工单失败", error);
    uni.showToast({
      title: "分配工单失败，请重试",
      icon: "none",
    });
  }
};

const hlHandler = async () => {
  try {
    const params = {
      uuid: receivedId.value,
      is_ignore: "1",
    };

    const res = await api.alarmUpdateById(params);
    console.log("忽略成功", res);

    workOrder.value.is_ignore = "1";
    alarmBasicData.value.自动分配工单 = "否";

    await getWorkOrderDetail(receivedId.value);
  } catch (error) {
    console.error("忽略失败", error);
    uni.showToast({
      title: "忽略失败，请重试",
      icon: "none",
    });
  }
};

let dealLineDialog = ref();
let dealList = ref<any[]>([]);

const dealLineHandler = async () => {
  try {
    // 调用 operationAlarmRecordslistDataByOperationAlarmId 方法
    const res = await api.operationAlarmRecordslistDataByOperationAlarmId({
      operationAlarmId: receivedId.value,
    });
    console.log("获取预警记录", res);

    // 清空处理列表
    dealList.value = [];

    // 根据返回的数据做数据处理
    res.data.map((item: any) => {
      let currItem: any = {};
      switch (item.action) {
        case "告警产生":
          currItem = {
            time: item.create_time,
            type: item.action,
            otherData: {
              告警详情: item.description,
              告警来源: item.distribution_form,
              上报人: item.user_mc,
              所属部门: item.org_mc,
            },
          };
          break;
        case "告警处理":
          currItem = {
            time: item.create_time,
            type: item.action,
            otherData: {
              处理内容: item.content,
              处理人: item.user_mc,
              处理情况: item.tackle_details,
            },
          };
          break;
        case "转处理":
          currItem = {
            time: item.create_time,
            type: item.action,
            otherData: {
              处理内容: item.content,
              处理人: item.user_mc,
              处理详情: item.tackle_details,
            },
          };
          break;
      }
      dealList.value.push(currItem);
    });

    // 打开处理过程对话框
    dealLineDialog.value.open(dealList.value);
  } catch (error) {
    console.error("获取预警记录失败", error);
  }
};
</script>

<style lang="scss" scoped>
.work-order-detail {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #f4f6fa;
  box-sizing: border-box;

  .work-order-detail-contet {
    flex: 1;
    overflow: auto;
  }

  .detail-header {
    display: flex;
    align-items: center;
    padding: 20px;
    background-color: white;

    .back-btn {
      margin-right: 20px;
    }

    .title {
      font-size: 18px;
    }
  }

  :deep(.uni-section) {
    background: #ffffff;
    box-shadow: 0rpx 2rpx 8rpx 0rpx rgba(0, 12, 39, 0.06);
    border-radius: 20rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
    .uni-section-content {
      padding: 32rpx 30rpx;
    }
    .uni-section-header {
      padding: 0;
    }
    &.section-base {
      .uni-section-header {
        height: 75rpx;
        line-height: 75rpx;
        padding: 0;
        background: #5e93ff;
        padding-left: 40rpx;
        .uni-section__content-title {
          font-weight: 500;
          font-size: 30rpx !important;
          color: #ffffff !important;
        }
      }
    }
  }

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    &:last-child {
      margin-bottom: 0;
    }
    .label {
      font-weight: 400;
      font-size: 30rpx;
      color: #333333;
      line-height: 42rpx;
    }

    .value {
      flex: 1;
      font-size: 28rpx;
      color: #666666;
    }
  }
  .uni-forms-item {
    &.textarea-desc {
      margin-bottom: 0 !important;
    }
  }
  .uni-forms-item__label {
    width: 90px !important;
  }

  .action-section {
    width: 100%;
    height: 100%;
    text-align: right;
    align-items: center;
    display: flex;
    justify-content: flex-end;
  }
  .deal-status {
    display: flex;
    justify-content: space-between;
    width: 100%;
    .info-item {
      margin-bottom: 0;
    }
    uni-button[type="primary"] {
      margin-right: 0;
    }
  }

  .module-img-video {
    padding-bottom: 100rpx;
    margin-bottom: 0;
    :deep(.uni-forms-item__content) {
      position: static;
    }
  }
}
</style>
